"""
解决cv2.imwrite的中文路径报错问题
"""

import cv2
import numpy as np
import os


def conv_bgr2rgb(img_arr):
    img_arr = cv2.cvtColor(img_arr, cv2.COLOR_BGR2RGB)
    return img_arr


def show_img(img_arr, title="img", resize=(1280, 720), bgr2rgb=True):
    if resize:
        img_arr = cv2.resize(img_arr, resize)
    if bgr2rgb:
        img_arr = conv_bgr2rgb(img_arr)
    cv2.imshow(title, img_arr)
    cv2.waitKey(0)
    cv2.destroyAllWindows()


def get_file_name_and_extension(file_path):
    splitext = os.path.splitext(os.path.basename(file_path))
    assert len(splitext) > 1, '没有文件后缀名?'
    file_name, file_extension = splitext
    return file_name, file_extension


def resize_image(img_arr, resize=(600, 400)):
    img_arr = cv2.resize(img_arr, resize)
    return img_arr


def crop_image(image, coordinates):
    if isinstance(image, str):
        # 读取图像
        image = read_image(image)
        if image is None:
            print("*** crop_image Error: Unable to read the image.")
            return None

    # 提取坐标
    (x0, y0), (x1, y1) = coordinates

    # 截取图像的指定部分
    cropped_image = image[y0:y1, x0:x1]

    return cropped_image


def read_image(img_path):
    img = cv2.imdecode(np.fromfile(img_path, dtype=np.uint8), cv2.IMREAD_COLOR)
    return img


def save_image(img_path, img):
    file_name, file_extension = get_file_name_and_extension(img_path)
    cv2.imencode(file_extension, img)[1].tofile(img_path)


if __name__ == '__main__':
    # src_img = read_image('E:\\猫狗数据集\\1.png')
    # dst_dir = 'E:\\猫狗数据集复制\\'
    # save_image(dst_dir,src_img)

    img_path = '../tempdir/recorded_states/screen_image/心.png'
    img_arr = read_image(img_path)

    dst_path = '../tempdir/recorded_states/screen_image/心1.png'
    save_image(dst_path, img_arr)

